package com.centit.jddtgzsz.controller;

import com.centit.jddtgzsz.po.JddtGzsz;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.centit.jddtgzsz.service.JddtGzszManager;
import com.centit.jksxgl.po.JddtJksxgl;
import com.centit.jksxgl.service.JddtJksxglManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.centit.airplanebaseinfo.po.AirplaneBaseinfo;
import com.centit.cxtj.service.CxtjManager;
import com.centit.dtjktxlog.po.JddtDtjktxlog;
import com.centit.dtjktxlog.service.JddtDtjktxlogManager;
import com.centit.framework.common.JsonResultUtils;
import com.centit.framework.common.ResponseMapData;
import com.centit.framework.components.CodeRepositoryUtil;
import com.centit.framework.core.controller.BaseController;
import com.centit.framework.core.dao.DictionaryMapUtils;
import com.centit.framework.security.model.CentitUserDetails;
import com.centit.support.algorithm.UuidOpt;
import com.centit.support.database.utils.PageDesc;
import com.centit.util.LayuiResultUtil;
import com.centit.util.SendEmail;

/**
 * JddtGzsz  Controller.
 * create by scaffold 2020-03-10 
 * @author 脚手架，改成开发者的名字
 * T_JDDT_GZSZ【机队动态监控规则设置表】机队动态监控规则设置表   
*/


@Controller
@RequestMapping("/jddtgzsz/jddtgzsz")
public class JddtGzszController  extends BaseController {
	private static final Log log = LogFactory.getLog(JddtGzszController.class);
	
	@Resource
	private JddtGzszManager jddtGzszMag;
	@Resource
	private JddtJksxglManager jddtJksxglMag;
	@Autowired
	private JddtDtjktxlogManager jddtDtjktxlogMag;
	
	@Autowired
	private CxtjManager cxtjMag;
	

    /**
     * 查询所有   T_JDDT_GZSZ【机队动态监控规则设置表】  列表
     *
     * @param field    json中只保存需要的属性名
     * @param request  {@link HttpServletRequest}
     * @param response {@link HttpServletResponse}
     * @return {data:[]}
     */
    @RequestMapping(method = RequestMethod.GET)
    public void list(String[] field, PageDesc pageDesc, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> searchColumn = convertSearchColumn(request);  
        searchColumn.put("dataValid", "T");
        JSONArray jsonArrayObjects = jddtGzszMag.getJSONArrayList( searchColumn, pageDesc);
        if (null == pageDesc) {
            JsonResultUtils.writeSingleDataJson(jsonArrayObjects, response);
            return;
        }
        for(int i=0; i<jsonArrayObjects.size(); i++) {
        	JSONObject obj = jsonArrayObjects.getJSONObject(i);
        	obj.put("txtypeText", CodeRepositoryUtil.getValue("TXTYPE", obj.getString("txtype")));
        	obj.put("txdayText", "提前"+obj.getString("txday")+"天");
        }
        ResponseMapData resData = new ResponseMapData();
        resData.addResponseData(OBJLIST, jsonArrayObjects);
        resData.addResponseData(PAGE_DESC, pageDesc);
        LayuiResultUtil.layuiwriteResponseDataAsJson(resData, pageDesc, response);
    }
    
    /**
     * 查询单个  T_JDDT_GZSZ【机队动态监控规则设置表】 
	
	 * @param recId  REC_ID
     *  
     * 
     * @param response    {@link HttpServletResponse}
     * @return {data:{}}
     */
    @RequestMapping(value = "/{recId}", method = {RequestMethod.GET})
    public void getJddtGzsz(@PathVariable String recId, HttpServletResponse response, HttpServletRequest request) {
    	String eric = request.getParameter("eric");
    	Map<String, Object> searchColumn = new HashMap<String, Object>();
    	searchColumn.put("dataValid", "T");
    	List<JddtJksxgl> jddtJksxglList = jddtJksxglMag.listObjects(searchColumn);
    	request.setAttribute("jddtJksxglList", jddtJksxglList);
    	try {
	    	if("add".equals(eric)) {
				request.getRequestDispatcher("/modules/jddtgzsz/jddtgzszInfo.jsp").forward(request, response);
	    	} else {
	    		JddtGzsz jddtGzsz = jddtGzszMag.getObjectById( recId);
	    		request.setAttribute("jddtGzsz", jddtGzsz);
	    		if ("view".equals(eric)){
	       			request.getRequestDispatcher("/modules/jddtgzsz/jddtgzszView.jsp").forward(request, response);
	       		}else if("edit".equals(eric)){
	       			request.getRequestDispatcher("/modules/jddtgzsz/jddtgzszInfo.jsp").forward(request, response);
	            }
	    	}
    	} catch (Exception e) {
			e.printStackTrace();
		} 
    }
    
    /**
     * 删除单个  T_JDDT_GZSZ【机队动态监控规则设置表】 
	
	 * @param recId  REC_ID
     */
    @RequestMapping(value = "/{recId}", method = {RequestMethod.DELETE})
    public void deleteJddtGzsz(@PathVariable String recId, HttpServletResponse response, HttpServletRequest request) {
    	CentitUserDetails cud = getLoginUser(request);
    	JddtGzsz jddtGzsz = jddtGzszMag.getObjectById( recId);
    	jddtGzsz.setDelTime(new Date());
    	jddtGzsz.setDelUsercode(cud.getUserCode());
    	jddtGzsz.setDataValid("F");
    	jddtGzszMag.mergeObject(jddtGzsz);
        JsonResultUtils.writeSingleDataJson("操作成功",response);
    } 
    
    /**
     * 新增或保存 T_JDDT_GZSZ【机队动态监控规则设置表】 
    
	 * @param recId  REC_ID
	 * @param jddtGzsz  {@link JddtGzsz}
     * @param response    {@link HttpServletResponse}
     */
    @RequestMapping(value = "/{recId}", method = {RequestMethod.PUT})
    public void updateJddtGzsz(@PathVariable String recId, 
    	@Valid JddtGzsz jddtGzsz, HttpServletResponse response, HttpServletRequest request) {
    	CentitUserDetails cud = getLoginUser(request);
    	JddtGzsz dbJddtGzsz = jddtGzszMag.getObjectById( recId);
        if (null != dbJddtGzsz) {//如果数据库数据存在，则是更新操作
        	dbJddtGzsz.copyNotNullProperty(jddtGzsz);//赋值页面不为空的值，小心页面空的字符串或者改写copyNotNullProperty方法，根据自己业务需要
        	dbJddtGzsz.setEditTime(new Date());
        	dbJddtGzsz.setEditUsercode(cud.getUserCode());
        	jddtGzszMag.mergeObject(dbJddtGzsz);
        	if(dbJddtGzsz.getStatus().equals("1")){
        		djjkdata(dbJddtGzsz.getRecId());
        	}
        } else {
        	jddtGzsz.setRecId(UuidOpt.getUuidAsString32());
        	jddtGzsz.setInsTime(new Date());
        	jddtGzsz.setInsUsercode(cud.getUserCode());
        	jddtGzsz.setDataValid("T");
        	jddtGzszMag.saveNewObject(jddtGzsz);//新增,注意主键赋值 UuidUtil.getTimeBasedUuid()，填写自己的业务时间，业务操作人等信息
        	if(jddtGzsz.getStatus().equals("1")){
        		djjkdata(jddtGzsz.getRecId());
        	}
        }
        JsonResultUtils.writeSingleDataJson("操作成功",response);
    }
    
    
    @RequestMapping(value = "/getJksxglList", method = {RequestMethod.GET})
    @ResponseBody
    public List<JddtJksxgl> getJksxglList(){
    	Map<String, Object> searchColumn = new HashMap<String, Object>();
    	searchColumn.put("dataValid", "T");
    	return jddtJksxglMag.listObjects(searchColumn);
    }
    
    @RequestMapping(value = "/turnOnOrOff/{recId}", method = {RequestMethod.GET})
    public void turnOnOrOff(@PathVariable String recId, HttpServletResponse response){
    	JddtGzsz jddtGzsz = jddtGzszMag.getObjectById( recId);
    	if("0".equals(jddtGzsz.getStatus())) {
    		jddtGzsz.setStatus("1");
    	} else if("1".equals(jddtGzsz.getStatus())) {
    		jddtGzsz.setStatus("0");
    	}
    	jddtGzszMag.updateObject(jddtGzsz);
    	JsonResultUtils.writeSingleDataJson("操作成功",response);
    }
    
    public  void djjkdata(String recId) { 
		//先查询监控规则 然后遍历
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("dataValid", "T");
		map.put("status", "1");
		map.put("recId", recId);
		JSONArray jddtGzszs = jddtGzszMag.getJSONArrayList(map,null); 
		for (int i = 0; i < jddtGzszs.size(); i++) {
			JSONObject jsonObject = jddtGzszs.getJSONObject(i);
			//根据规则名称来判断要监控什么字段
			if("飞机三证监控规则".equals(jsonObject.getString("sxname"))) {
				//获取对应的 预警期限时间
				String limitString = jsonObject.getString("txday");
				int days = Integer.valueOf(getNumeric(limitString));
				Map<String, Object> filterMap = new HashMap<String, Object>();
				filterMap.put("dataValid", "T");
				filterMap.put("status", "2");
				filterMap.put("szdqsj", days);  //dtyxDate  电台执照有效日期
				//此处 listObject方法暂时占位置 之后需要些方法 进行规定字段的日期查询 
				List<AirplaneBaseinfo> listObjects = cxtjMag.listObjects(filterMap);
				for (AirplaneBaseinfo airplaneBaseinfo : listObjects) {	
					//获取之前 已经插入过得提醒数据（未处理）
					Map<String, Object> getObjMap = new HashMap<String, Object>();
					getObjMap.put("airId", airplaneBaseinfo.getRecId());
					getObjMap.put("jksxId", jsonObject.getString("sxcode"));
					getObjMap.put("clStatus", "1");
					JddtDtjktxlog dbdtjktxlog = jddtDtjktxlogMag.getObjectByProperties(getObjMap);
					if(dbdtjktxlog != null) {
						//再次发起自动提醒
						if(jsonObject.getString("txtype").equals("1")) {
							//短信提醒
							System.out.println("发送三证到期短信提醒2");
						}
						if(jsonObject.getString("txtype").equals("2")) {
							//邮件提醒
							try {
								SendEmail.sendEmail("您的飞机三证时间即将过期，请及时处理", "411527091@qq.com");
							} catch (Exception e) {
								System.out.println("邮件发送失败");
								e.printStackTrace();
							}
						}
						if(jsonObject.getString("txtype").equals("3")) {
							//站内消息提醒
							
						}
						//log记录
						if(jsonObject.getString("alarmR")==null||StringUtils.isBlank(jsonObject.getString("alarmR"))){
							dbdtjktxlog.setAlarmR(0);
						}else{
							dbdtjktxlog.setAlarmR(Integer.parseInt(jsonObject.getString("alarmR")));
						}
						if(jsonObject.getString("alarmY")==null||StringUtils.isBlank(jsonObject.getString("alarmY"))){
							dbdtjktxlog.setAlarmR(0);
						}else{
							dbdtjktxlog.setAlarmR(Integer.parseInt(jsonObject.getString("alarmY")));
						}
						dbdtjktxlog.setZdtxTime(dbdtjktxlog.getZdtxTime()+1);//提醒完了自动提醒次数加一
						dbdtjktxlog.setZjtxDate(new Date());				//自动提醒的最后一次提醒时间
						if(airplaneBaseinfo.getDtyxDate()==null){
							continue;
						}
						int syday = differentDaysByMillisecond(new Date(),airplaneBaseinfo.getDtyxDate());
						if(syday<0) {
							dbdtjktxlog.setJcStatus("2"); 						//已到期
						}
						dbdtjktxlog.setSyday((long)syday); //剩余天数
						dbdtjktxlog.setTxType(jsonObject.getString("txtype"));
						jddtDtjktxlogMag.updateObject(dbdtjktxlog);
					} else {
						//发起提醒
						if(jsonObject.getString("txtype").equals("1")) {
							//短信提醒
							System.out.println("发送三证到期短信提醒");
						}
						if(jsonObject.getString("txtype").equals("2")) {
							//邮件提醒
							try {
								SendEmail.sendEmail("您的飞机三证时间即将过期，请及时处理", "411527091@qq.com");
							} catch (Exception e) {
								System.out.println("邮件发送失败");
								e.printStackTrace();
							}
						}
						if(jsonObject.getString("txtype").equals("3")) {
							//站内消息提醒
							
						}
						//log记录
						JddtDtjktxlog dtjktxlog = new JddtDtjktxlog();
						dtjktxlog.setRecId(UuidOpt.getUuidAsString32());
						dtjktxlog.setAirId(airplaneBaseinfo.getRecId()); 	//飞机id
						dtjktxlog.setClStatus("1");							//未处理
						dtjktxlog.setDataValid("T");						//有效性
						dtjktxlog.setZdtxTime((long)1);						//自动提醒次数
						dtjktxlog.setZjtxDate(new Date());					//自动提醒的最后一次提醒时间
						dtjktxlog.setJksxId(jsonObject.getString("sxcode"));//检测事项id
						if(airplaneBaseinfo.getDtyxDate()==null){
							continue;
						}
						if(jsonObject.getString("alarmR")==null||StringUtils.isBlank(jsonObject.getString("alarmR"))){
							dtjktxlog.setAlarmR(0);
						}else{
							dtjktxlog.setAlarmR(Integer.parseInt(jsonObject.getString("alarmR")));
						}
						if(jsonObject.getString("alarmY")==null||StringUtils.isBlank(jsonObject.getString("alarmY"))){
							dtjktxlog.setAlarmR(0);
						}else{
							dtjktxlog.setAlarmR(Integer.parseInt(jsonObject.getString("alarmY")));
						}
						dtjktxlog.setDqDate(airplaneBaseinfo.getDtyxDate());//到期时间即为电台有效时间
						dtjktxlog.setSctxDate(new Date()); 					//首次提醒时间
						
						int syday = differentDaysByMillisecond(new Date(),airplaneBaseinfo.getDtyxDate());
						if(syday>=0) {
							dtjktxlog.setJcStatus("1"); 						//快到期
						} else {
							dtjktxlog.setJcStatus("2"); 						//已到期
						}
						dtjktxlog.setSyday((long)syday); //剩余天数
						dtjktxlog.setTxType(jsonObject.getString("txtype"));
						dtjktxlog.setInsTime(new Date());
						jddtDtjktxlogMag.saveNewObject(dtjktxlog);
					}
					
				}
				
			}
			if("飞机合同监控规则".equals(jsonObject.getString("sxname"))) {
				String limitString = jsonObject.getString("txday");
				int days = Integer.valueOf(getNumeric(limitString));
				Map<String, Object> filterMap = new HashMap<String, Object>();
				filterMap.put("dataValid", "T");
				filterMap.put("status", "2");
				filterMap.put("htdqsj", days);  //htdqsj  电台执照有效日期
				//此处 listObject方法暂时占位置 之后需要些方法 进行规定字段的日期查询 
				List<AirplaneBaseinfo> listObjects = cxtjMag.listObjects(filterMap);
				for (AirplaneBaseinfo airplaneBaseinfo : listObjects) {	
					//获取之前 已经插入过得提醒数据（未处理）
					Map<String, Object> getObjMap = new HashMap<String, Object>();
					getObjMap.put("airId", airplaneBaseinfo.getRecId());
					getObjMap.put("jksxId", jsonObject.getString("sxcode"));
					getObjMap.put("clStatus", "1");
					JddtDtjktxlog dbdtjktxlog = jddtDtjktxlogMag.getObjectByProperties(getObjMap);
					if(dbdtjktxlog != null) {
						//再次发起自动提醒
						if(jsonObject.getString("txtype").equals("1")) {
							//短信提醒
							System.out.println("发送合同到期短信提醒2");
						}
						if(jsonObject.getString("txtype").equals("2")) {
							//邮件提醒
							try {
								SendEmail.sendEmail("您的飞机合同时间即将过期，请及时处理", "411527091@qq.com");
							} catch (Exception e) {
								System.out.println("邮件发送失败");
								e.printStackTrace();
							}
						}
						if(jsonObject.getString("txtype").equals("3")) {
							//站内消息提醒
							
						}
						//log记录
						if(jsonObject.getString("alarmR")==null||StringUtils.isBlank(jsonObject.getString("alarmR"))){
							dbdtjktxlog.setAlarmR(0);
						}else{
							dbdtjktxlog.setAlarmR(Integer.parseInt(jsonObject.getString("alarmR")));
						}
						if(jsonObject.getString("alarmY")==null||StringUtils.isBlank(jsonObject.getString("alarmY"))){
							dbdtjktxlog.setAlarmR(0);
						}else{
							dbdtjktxlog.setAlarmR(Integer.parseInt(jsonObject.getString("alarmY")));
						}
						dbdtjktxlog.setZdtxTime(dbdtjktxlog.getZdtxTime()+1);//提醒完了自动提醒次数加一
						dbdtjktxlog.setZjtxDate(new Date());				//自动提醒的最后一次提醒时间
						if(airplaneBaseinfo.getEndTime()==null){
							continue;
						}
						int syday = differentDaysByMillisecond(new Date(),airplaneBaseinfo.getEndTime());
						if(syday<0) {
							dbdtjktxlog.setJcStatus("2"); 						//已到期
						}
						dbdtjktxlog.setSyday((long)syday); //剩余天数
						dbdtjktxlog.setTxType(jsonObject.getString("txtype"));
						jddtDtjktxlogMag.updateObject(dbdtjktxlog);
					} else {
						//发起提醒
						if(jsonObject.getString("txtype").equals("1")) {
							//短信提醒
							System.out.println("发送合同到期短信提醒");
						}
						if(jsonObject.getString("txtype").equals("2")) {
							//邮件提醒
							try {
								SendEmail.sendEmail("您的飞机合同时间即将过期，请及时处理", "411527091@qq.com");
							} catch (Exception e) {
								System.out.println("邮件发送失败");
								e.printStackTrace();
							}
						}
						if(jsonObject.getString("txtype").equals("3")) {
							//站内消息提醒
							
						}
						//log记录
						JddtDtjktxlog dtjktxlog = new JddtDtjktxlog();
						if(jsonObject.getString("alarmR")==null||StringUtils.isBlank(jsonObject.getString("alarmR"))){
							dtjktxlog.setAlarmR(0);
						}else{
							dtjktxlog.setAlarmR(Integer.parseInt(jsonObject.getString("alarmR")));
						}
						if(jsonObject.getString("alarmY")==null||StringUtils.isBlank(jsonObject.getString("alarmY"))){
							dtjktxlog.setAlarmR(0);
						}else{
							dtjktxlog.setAlarmR(Integer.parseInt(jsonObject.getString("alarmY")));
						}
						dtjktxlog.setRecId(UuidOpt.getUuidAsString32());
						dtjktxlog.setAirId(airplaneBaseinfo.getRecId()); 	//飞机id
						dtjktxlog.setClStatus("1");							//未处理
						dtjktxlog.setDataValid("T");						//有效性
						dtjktxlog.setZdtxTime((long)1);						//自动提醒次数
						dtjktxlog.setZjtxDate(new Date());					//自动提醒的最后一次提醒时间
						dtjktxlog.setJksxId(jsonObject.getString("sxcode"));//检测事项id
						if(airplaneBaseinfo.getEndTime()==null){
							continue;
						}
						dtjktxlog.setDqDate(airplaneBaseinfo.getEndTime());	//到期时间即为合同到期时间
						dtjktxlog.setSctxDate(new Date()); 					//首次提醒时间
						
						int syday = differentDaysByMillisecond(new Date(),airplaneBaseinfo.getEndTime());
						if(syday>=0) {
							dtjktxlog.setJcStatus("1"); 						//快到期
						} else {
							dtjktxlog.setJcStatus("2"); 						//已到期
						}
						dtjktxlog.setSyday((long)syday); //剩余天数
						dtjktxlog.setTxType(jsonObject.getString("txtype"));
						dtjktxlog.setInsTime(new Date());
						jddtDtjktxlogMag.saveNewObject(dtjktxlog);
					}
				}
			}
		}
	}
    /**
	 * 过滤非数字
	 * @param str
	 * @return
	 */
	public static String getNumeric(String str) {
	    String regEx="[^0-9]";  
	    Pattern p = Pattern.compile(regEx);  
	    Matcher m = p.matcher(str);  
	    return m.replaceAll("").trim();
	}
		
	/**
	 * 求日期时间差 -天
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int differentDaysByMillisecond(Date date1,Date date2){
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
        return days;
    }
}
